package study.web.service.socket.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**  
* @Name: WeatherServer
* @Description: 天气查询服务（socket实现）
* @Author: 李超
* @version 1.0
* @Create Date: 2017-01-06
*/
public class WeatherServer {
	
	public static void main(String[] args) throws IOException {
		//启动socket服务：自定义端口号建议10000以上
		ServerSocket serverSocket = new ServerSocket(12345) ;
		System.out.println("启动Socket服务...");
		DataInputStream dataInputStream = null ;
		DataOutputStream dataOutputStream = null ;
		while(true) {
			try {
				//监听客户端连接，accept()方法是一个阻塞方法
				Socket socket = serverSocket.accept() ;
				//准备接受数据的流
				dataInputStream = new DataInputStream(socket.getInputStream()) ;
				//准备发送数据的流
				dataOutputStream = new DataOutputStream(socket.getOutputStream()) ;
				//接受客户端请求的数据（城市名称）
				String cityName = dataInputStream.readUTF() ;
				System.out.println("from client ... " + cityName);
				//处理数据 ... 休眠1秒
				Thread.sleep(3000) ;
				String result = "多云" ;
				//给客户端响应数据
				dataOutputStream.writeUTF(result) ;
				System.out.println("to client ... " + result);
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				//释放资源
				if(dataInputStream != null) {
					dataInputStream.close() ;
				}
				if(dataOutputStream != null) {
					dataOutputStream.close() ;
				}
				//socket连接在服务端一般是不用主动关闭的，等待客户端关闭链接
			}
		}
	}
}
